﻿using System;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;

namespace HYTools
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdInvertSelection : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				Document document = cmdData.Application.ActiveUIDocument.Document;
				transaction = new Transaction(document);
				transaction.Start("Invert Selection");
				ElementSet allModelElements = this.GetAllModelElements(cmdData);
				Selection selection = cmdData.Application.ActiveUIDocument.Selection;
				foreach (ElementId elementId in selection.GetElementIds())
				{
					if (allModelElements.Contains(document.GetElementById(elementId)))
					{
						allModelElements.Erase(document.GetElementById(elementId));
					}
				}
				RevitVersionFuncs.ClearSelection(selection);
				foreach (object obj in allModelElements)
				{
					Element element = (Element)obj;
					RevitVersionFuncs.AddToSelection(selection, element);
				}
				transaction.Commit();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		private ElementSet GetAllModelElements(ExternalCommandData cmdData)
		{
			ElementSet elementSet = cmdData.Application.Application.Create.NewElementSet();
			foreach (Element element in new FilteredElementCollector(cmdData.Application.ActiveUIDocument.Document, cmdData.Application.ActiveUIDocument.ActiveView.Id).WhereElementIsNotElementType().ToElements())
			{
				if (!(element.GetType() == typeof(ElectricalSystem)) && !(element.GetType() == typeof(MechanicalSystem)) && !(element.GetType() == typeof(PipingSystem)))
				{
					elementSet.Insert(element);
				}
			}
			return elementSet;
		}
	}
}
